import os
import random
from django.http import JsonResponse,HttpResponse
from django.shortcuts import redirect
from django.views import View
from django_redis import get_redis_connection
from fdfs_client.client import Fdfs_client
from rest_framework import status
from rest_framework.generics import CreateAPIView, RetrieveUpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from tenth_power.utils.fastdfs.storage import FastDFSStorage
from users.models import User
from users.serializers import CreateUserSerializer, PersonSerializer

import logging
logger = logging.getLogger('django')


class SMSCodeView(View):
    def get(self, request, mobile):

        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:
            return JsonResponse({'code': 400,
                                 'message': '短信验证码发送过于频繁'})

        # 生成保存并发送短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info('短信验证码为：%s' % sms_code)

        # 保存短信验证码
        pl = redis_conn.pipeline()

        # 保存短信验证码(添加到管道中)
        pl.set('sms_%s' % mobile, sms_code, 300)
        # 设置短信发送的标记，有效期为：60s(添加到管道中)
        pl.set('send_flag_%s' % mobile, 1, 60)

        # 执行redis pipeline请求
        pl.execute()
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code)

        # ④ 返回响应结果
        return JsonResponse({
                     'success': 'true',
                     'message': 'ok',
                     'sms_code': sms_code
                    })


class UserView(CreateAPIView):
    """
    用户注册
    """
    serializer_class = CreateUserSerializer


class UserRetrieveUpdateAPIView(RetrieveUpdateAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = PersonSerializer

    def retrieve(self, request, *args, **kwargs):
        serializer = self.serializer_class(request.user)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        serializer = self.serializer_class(request.user, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

class PasswordAPIView(APIView):
    def put(self,request):
        password = request.data['password']
        id = request.user.id
        user = User.objects.get(id=id)
        if len(password) > 20 or len(password) < 8:
            return Response({'message': '密码长度需要8～20位'}, status=status.HTTP_403_FORBIDDEN)
        user.set_password(password)
        user.save()
        return Response(status=status.HTTP_200_OK)

class UsernameCountView(APIView):
    """
    用户名数量
    """
    def get(self,request, username):
        """
        获取指定用户名数量
        """
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count
        }

        return Response(data)


class AvatarView(APIView):
    def post(self, request):
        pic = request.data['img']
        pic = pic.read()
        client = Fdfs_client(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'utils/fastdfs/client.conf'))
        nginx_url = 'http://192.168.19.131:8888/'
        try:
            ret = client.upload_by_buffer(pic)['Remote file_id']
            User.objects.filter(id=request.user.id).update(avatar=ret)
        except Exception as e:
            return JsonResponse({
                "errno": 400,
                "errmsg": "图片上传失败"
            })
        return JsonResponse({
            "imgurl": nginx_url + ret
        })


# 前端富文本编辑器上传图片  /upload/common/

class CommonView(APIView):
    def post(self, request):
        upload = request.data.get('upload')
        # 将图片信息上传并且返回数据
        storage = FastDFSStorage()
        # 获取图片名称
        image_name = storage.save(name=upload.name, content=upload)
        image_url = storage.url(image_name)
        # 组织响应
        data = "http://127.0.0.1:8080/upload_success.html?" + \
               "image_url" + "=" + image_url + "&CKEditorFuncNum=1"
        return redirect(data)


# POST /users/like/{id}/
# DELETE /users/like/{id}/
class UsersLikeViewSet(APIView):
    def post(self,request,pk):
        user = User.objects.get(id=pk)
        fans = user.idols.add(request.user.id)
        return Response({
            "message": "关注成功",
            "success": "true"
        })
    def delete(self,request,pk):
        user = User.objects.get(id=pk)
        fans = user.idols.remove(request.user.id)
        return Response({
            "message": "取消关注成功",
            "success": "true"
        })


